<template>
    <div>
        <!--        面包屑导航-->
        <breadcrumb :navData="['权限管理','角色列表']"></breadcrumb>
        <!--        卡片区域-->
        <el-card class="box-card">
            <!--            添加-->
            <el-button type="primary" @click="addRolesVisible = true">添加角色</el-button>
            <!--角色列表-->
            <el-table
                :data="rolesData"
                border>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row style="display: flex;align-items: center" class="borderStyle"
                                v-for="(item1,index1) in scope.row.children" :key="item1.id">
                            <!--                            一级权限-->
                            <el-col style="text-align: center" :span="6">
                                <el-tag closable effect="dark" @close="onDeleteRolesRight(scope.row,item1.id)">
                                    {{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--                            二级和三级权限-->
                            <el-col class="leftBorder" :span="18">
                                <el-row class="topBorder" v-for="item2 in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag closable type="success" effect="dark"
                                                @close="onDeleteRolesRight(scope.row,item2.id)">
                                            {{ item2.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag closable v-for="item3 in item2.children" :key="item3.id" type="warning"
                                                effect="dark" @close="onDeleteRolesRight(scope.row,item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        <!--                        <pre>{{scope.row}}</pre>-->
                        <!--                        渲染角色权限-->

                    </template>
                </el-table-column>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <!--                        编辑-->
                        <el-button type="primary" size="mini" @click="onEditRoles(scope.row)" icon="el-icon-edit">编辑
                        </el-button>
                        <!--                        删除-->
                        <el-button type="danger" size="mini" @click="onDeleteRoles(scope.row.id)" icon="el-icon-delete">
                            删除
                        </el-button>
                        <!--                        分配权限-->
                        <el-button type="warning" size="mini" icon="el-icon-setting"
                                   @click="showSetRightDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!--        添加或者编辑角色-->
        <el-dialog :before-close="addRolesClose" :title="addRoles.roleId?'编辑角色':'添加角色'" :visible.sync="addRolesVisible">
            <el-form :model="addRoles" :rules="addRolesRules" ref="addRolesForm" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoles.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoles.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addRolesClose">取 消</el-button>
                <el-button type="primary" @click="onAddRoles">确 定</el-button>
            </div>
        </el-dialog>

        <!--        分配权限对话框-->
        <el-dialog @close="onSetRightDialogClose" title="分配权限" :visible.sync="setRightVisible" destroy-on-close>
            <!--            <el-tree 树形控件
                            :data="rightData" 数据源
                            show-checkbox 显示复选框
                            node-key="id" 设置唯一值
                            default-expand-all 默认展开所有节点
                            :default-checked-keys="defKeys" 默认被选中的项(数据类型:数组)
                            :props="treeProps" 数据源默认属性对应关系>
                        </el-tree>-->
            <el-tree
                ref="treeRef"
                :data="rightData"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="defKeys"
                :props="treeProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setRightVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSentRolesRight">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "Roles",
    data() {
        return {
            //角色列表数据源
            rolesData: [],
            //添加角色对话框显示隐藏
            addRolesVisible: false,
            addRoles: {
                roleId: null,
                roleName: "",
                roleDesc: ""
            },
            addRolesRules: {
                roleName: [
                    {required: true, message: '请输入角色名称', trigger: 'blur'},
                    {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
                ],
                roleDesc: [
                    {required: true, message: '请输入角色描述', trigger: 'blur'},
                    {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
                ]
            },
            //分配权限对话框显示隐藏
            setRightVisible: false,
            //分配权限数据源
            rightData: [],
            //树形控件属性绑定
            treeProps: {
                //设置label的值来设置树形节点的文本展示
                label: 'authName',
                //设置children的值来展示子节点信息
                children: 'children'
            },
            //设置树形控件中默认被选中的内容
            defKeys: [],
            //当前要分配权限的角色id
            rolesId: null
        }
    },
    created() {
        this.getRolesList();
    },
    methods: {
        //获取角色列表
        async getRolesList() {
            let {data: res} = await this.$http.get("roles")
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.rolesData = res.data;
        },
        //获取所有权限列表(树形);
        async getRightDataList() {
            let {data: res} = await this.$http.get("rights/tree")
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.rightData = res.data;
        },
        /**
         * 删除权限
         * @param row 行数据 可以取出角色id
         * @param rightId 权限id
         */
        async onDeleteRolesRight(row, rightId) {
            let roleId = row.id;//角色ID
            let {data: res} = await this.$http.delete(`roles/${roleId}/rights/${rightId}`);
            console.log(res);
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.$message.success(res.meta.msg)
            row.children = res.data;
        },
        //确定添加或者编辑角色
        onAddRoles() {
            this.$refs.addRolesForm.validate(async (valid) => {
                //如果valid为true 则表示整个表单内的校验都通过了
                if (!valid) return;
                //通过校验
                let obj;
                let roleId = this.addRoles.roleId;
                if (roleId) {//编辑
                    obj = await this.$http.put(`roles/${roleId}`, this.addRoles);
                } else {//添加
                    obj = await this.$http.post("roles", this.addRoles);
                }
                let {data: res} = obj;
                if (res.meta.status !== 200 && res.meta.status !== 201) return this.$message.error(res.meta.msg);
                await this.getRolesList()
                this.$message.success(res.meta.msg);
                this.$refs.addRolesForm.resetFields();
                this.addRolesVisible = false;
            })
        },
        //编辑角色
        async onEditRoles(row) {
            let {data: res} = await this.$http.get(`roles/${row.id}`)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.addRoles.roleId = res.data.roleId
            this.addRoles.roleName = res.data.roleName
            this.addRoles.roleDesc = res.data.roleDesc
            this.addRolesVisible = true;
        },
        //删除角色
        async onDeleteRoles(roleId) {
            let result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            console.log(result);
            if (result !== "confirm") return this.$message.info("取消删除")
            //用户确定要删除操作
            let {data: res} = await this.$http.delete(`roles/${roleId}`)
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.getRolesList()
            this.$message.success(res.meta.msg);
        },
        //关闭弹窗的时候清空弹窗中的默认数据
        addRolesClose() {
            this.addRoles.roleId = null;
            this.addRoles.roleName = ""
            this.addRoles.roleDesc = ""
            console.log("=====>", this.addRoles);
            this.addRolesVisible = false;
        },
        //显示分配权限对话框
        showSetRightDialog(row) {
            //保存当前要分配权限的角色id
            this.rolesId = row.id;
            //获取所有权限列表(树形);
            this.getRightDataList();
            /* let newArr = [];
             rightList.forEach((item)=>{
                 newArr.push(item.children)
             })
             let newArr2 = [];
             newArr.forEach((item)=>{
                 newArr2.push(item.children)
             })
             newArr2.forEach((item)=>{
                 this.defKeys.push(item.id)
             })*/

            this.defKeys = [];
            this.getRolesRight(row);
            console.log(this.defKeys)
            // this.$refs.treeRef.setCheckedNodes(this.defKeys)
            this.setRightVisible = true;
        },

        //递归获取当前用户所有三级权限id
        getRolesRight(rightList) {
            //判断当前权限是否为三级节点
            if (!rightList.children) {
                return this.defKeys.push(rightList.id);
            }
            rightList.children.forEach((item) => {
                return this.getRolesRight(item);
            })
        },
        //关闭分配权限对话框
        onSetRightDialogClose() {
            //关闭分配权限对话框的时候清空所有选中状态
            this.defKeys = [];
        },
        //发送修改后的权限数据到后端
        async onSentRolesRight() {
            //获取树形组件
            let treeRef = this.$refs.treeRef;
            //获取所有被半选的权限id ==>数组
            // let halfCheckedKeys = treeRef.getHalfCheckedKeys();
            //获取所有选中状态的权限id ==>数组
            // let checkedKeys = treeRef.getCheckedKeys();
            //所有被选择的权限id
            // let keys = halfCheckedKeys.concat(checkedKeys)
            let keys = [
                ...treeRef.getHalfCheckedKeys(),
                ...treeRef.getCheckedKeys()
            ];
            //把所有被选中的权限id 通过,号分割成字符串
            let rids = keys.join(",")
            let {data: res} = await this.$http.post(`roles/${this.rolesId}/rights`, {
                rids: rids
            })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.getRolesList()
            this.$message.success(res.meta.msg);
            //关闭对话框
            this.setRightVisible = false;
        }
    }
}
</script>

<style scoped lang="scss">
.el-tag {
    margin: 6px;
    user-select: none;
}

.borderStyle {
    margin: 0 20px;
    border-top: 1px solid #eeeeee;
    border-left: 1px solid #eeeeee;
    border-right: 1px solid #eeeeee;

    &:last-child {
        border-bottom: 1px solid #eeeeee;
    }
}

.leftBorder {
    border-left: 1px solid #eeeeee;
}

.topBorder {
    border-top: 1px solid #eeeeee;

    &:first-child {
        border-top: none;
    }
}


</style>